import serial


def limitit(data,maxd,mind):
    if data>maxd:
        return maxd
    elif data<mind:
        return mind
    else:
        return data


def get_event(li, bps):
    portx = "COM6"
    #波特率，标准值之一：50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,19200,38400,57600,115200
    print(bps)
    #超时设置,None：永远等待操作，0为立即返回请求结果，其他值为等待超时时间(单位为秒）
    timex = 1
    # 打开串口，并得到串口对象
    ser = serial.Serial(portx, bps, timeout=timex)
    l1 = li[0]    # 5值
    l2 = li[1]  # 4值
    l3 = li[2]   # 3值
    l4 = li[3]    # 2值
    l5 = li[4]    # 1值
    l1i=int(limitit(l1,1.1,0)*1000+900)
    l2i=int(limitit(l2,1.5,0)*666+950)
    l3i=int(limitit(l3,1.5,0)*666+950)
    l4i=int(limitit(l4,1.2,0)*833+950)
    l5i=int(2000-limitit(l5,0.8,0)*1375)
    Uart_buf = bytearray([0x55, 0x55, 0x14, 0x03, 0x05, 0x00, 0x01,
                          0x01, l5i & 0x00ff,(l5i & 0xff00) >> 8,
                          0x02, l4i & 0x00ff,(l4i & 0xff00) >>8,
                          0x03, l3i & 0x00ff, (l3i & 0xff00) >>8,
                          0x04, l2i & 0x00ff, (l2i & 0xff00) >>8,
                          0x05, l1i & 0x00ff,(l1i & 0xff00) >>8]
                         )
    res = ser.write(Uart_buf)
    print(res)


if __name__=="__main__":
    bs = [50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,19200,38400,57600,115200]
    for b in bs:
        get_event([2, 0, 2, 0, 2], b)